// miniprogram/camera/camera.js
import  allEnigmas from '../../allEnigmas'
import upng from '../../UPNG.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tipShow: false,
    enigma: "四角轻轻，说话无音，人不对面，句句真心(打一物)",
    id: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.id = parseInt(options.id)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  tipOn: function() {
    this.setData({tipShow: true})
  },

  tipClose: function() {
    this.setData({tipShow: false})
  },

  takePhoto: function() {
    const context = wx.createCameraContext()
    context.takePhoto({
      quality: "normal",
      success: (res) => {
        this.transformBase64(res.tempImagePath)
        wx.showLoading({
          title: '识别中',
        })
      }
    }) 
  },
  transformBase64(res) {
    var FSM = wx.getFileSystemManager();
    let that = this;
    FSM.readFile({
      filePath: res,
      encoding: "base64",
      success: function(data) {
        let Working = data.data;
        that.searchPhoto(data.data)
        return Working;
      }
    });
  },

  searchPhoto: function(imageBase64) {
    let that = this;
    wx.request({
      url: 'https://cn1-crs.easyar.com:8443/search',
      data: {
        image: imageBase64
      },
         header: {
           'Authorization': 'vwtH9WlPAl8bnGd/p5AhAkCCYTov/lVNuPuGWGWBDr4IzszxxIJ6qNA9/nzrOiwak++NEA3G5XECfRYaMZj9Hw==',
           'content-type': 'application/json'
         },
      method: 'POST',
      success(res) {
        if (res.data.statusCode == 0) {
          wx.hideLoading({
            success: (res) => {},
          })
          setTimeout(() => {
            wx.showToast({
              title: '识别成功'
            })
            wx.navigateTo({
              url: '../getCard/getCard',
            })
          }, 500);
        } else if (res.data.statusCode != 0) {
            wx.hideLoading();
            wx.showToast({
              title: '没有找到正确的物体哟',
              icon: 'none'
            })
        }
      },
      fail(err) {
        wx.hideLoading({
          success: (res) => {},
        })
        wx.showToast({
          title: '网络不给力哟~',
        })
      },
      complete() {
        wx.hideLoading({
          success: (res) => {},
        })
      }
    })
  },
  back: function() {
    wx.navigateBack()
  }
})